package tech.ideashare.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tech.ideashare.model.WeChatInfo;
import tech.ideashare.utils.IS_HttpUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static tech.ideashare.base.APPCONST.*;
import static tech.ideashare.utils.SignUtils.sign;

/**
 * Created by lixiang01 on 2/22/2017.
 */
@Controller
@CrossOrigin
public class WXController extends BaseController{

//    private static final String appID= "wx9767d8078598c934";
//    private static final String appSecret= "f317f6ca2ea23c1d4fffcfd75a2e5447";


    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    @GetMapping(value = "wx/getAccessCode")
    @ResponseBody
    public void getAccessCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String callBackUrl = "http://www.ztyweb.cn/wx/getAccessCodeR";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appID
                +"&redirect_uri="+ URLEncoder.encode(callBackUrl)
                +"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        logger.info("向微信第一次请求");
        response.sendRedirect(url);
    }

    @GetMapping(value = "wx/getAccessCodeR")
    @ResponseBody
    public String getAccessCodeR(HttpServletRequest request, HttpServletResponse response)  {
        String result ="";
        try {
            String wx_code = request.getParameter("code");
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appID + "&secret=" + appSecret + "&code=" + wx_code + "&grant_type=authorization_code";
            result = IS_HttpUtils.getAsString(url,null);

            WeChatInfo weChatInfo = JSON.parseObject(result,WeChatInfo.class);
            request.getSession().setAttribute(WECHAT_INFO,weChatInfo);
            String backUrl  = (String) request.getSession().getAttribute(BACK_URL);
            logger.info("取出backUrl : "+backUrl);
            response.sendRedirect(backUrl);
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            return JSON.toJSONString(result);
        }
    }


    @GetMapping("/wxRedirct")
    @ResponseBody
    public String wxRedirct(@RequestParam String url, HttpServletRequest request, HttpServletResponse response) throws IOException {


        String jsapi_ticket = stringRedisTemplate.opsForValue().get(JSAPI_TICKET);

        if (jsapi_ticket == null || jsapi_ticket.equals("null")) {
            JSONObject result = IS_HttpUtils.getAsJson("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appID+"&secret="+appSecret,null);
            String accessToken =result.getString("access_token");

            JSONObject json_jsapi_ticket = IS_HttpUtils.getAsJson("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi",null);
            jsapi_ticket =json_jsapi_ticket.getString("ticket");
            stringRedisTemplate.opsForValue().set(JSAPI_TICKET,jsapi_ticket,7000, TimeUnit.SECONDS);
        }

        Map<String, String> ret = sign(jsapi_ticket, url);
        for (Map.Entry entry : ret.entrySet()) {
            System.out.println(entry.getKey() + ", " + entry.getValue());
        }
        ret.put("appId",appID);
        return JSON.toJSONString(ret);
    }
}
